package com.bugpool.leilema.freamwork.datascope.impl;

import com.bugpool.leilema.freamwork.datascope.DataScopeStrategy;
import com.bugpool.leilema.freamwork.datascope.DataScopeUtils;
import com.bugpool.leilema.tc.bean.dto.DataScopeDTO;

/**
 * @Author wh
 * @Description
 * @Date 2023/6/13 17:27
 * @Version 1.0
 **/
public class DeptAndChildDataScope extends AbstractDataScope  {
    @Override
    public StringBuilder sqlEnhance(DataScopeDTO dataScopeDTO) {
        StringBuilder sqlStringBuilder = dataScopeDTO.getSqlStringBuilder();
        //查询本部门 及本部门以下的数据
        sqlStringBuilder
                .append(" OR ")
                .append(dataScopeDTO.getTbAlias()+SUFFIX)    //主表别名
                .append("dept_id IN ( WITH RECURSIVE dept_tree AS (\n" +
                        "  -- 查询本部门\n" +
                        "  SELECT dept_id FROM tb_sys_dept WHERE dept_id =")
                .append(dataScopeDTO.getDeptId())
                .append("  UNION ALL\n" +
                        "  -- 查询本部门下的所有子部门\n" +
                        "  SELECT d.dept_id FROM dept_tree dt JOIN tb_sys_dept d ON dt.dept_id = d.parent_id\n" +
                        ")\n" +
                        "SELECT dept_id FROM dept_tree)");
        return sqlStringBuilder;
    }
}
